package cn.fyl.org.service.impl;

import cn.fyl.basic.service.impl.BaseServiceImpl;

import cn.fyl.org.domain.Department;
import cn.fyl.org.mapper.DepartmentMapper;
import cn.fyl.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;



//查询的方法比较多，使用查询的事务配置
//只读，事务传播机制=SUPPORTS，有我就用，没有事务就不用
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public void save(Department department) {
        departmentMapper.save(department);

        //更新数据库
        update(department);
    }
    @Override
    public void update(Department department) {

        if (department.getParent_id()==null){
            department.setDirPath("/"+department.getId());
        }else {
            // 获取上级部门id
            Long parent_id = department.getParent_id();
            // 根据上级部门id查找dirPath
            Department parentDept = departmentMapper.loadById(parent_id);
            String parent_dirPath = parentDept.getDirPath();
            // 组装自己的id
            department.setDirPath(parent_dirPath+"/"+department.getId());
        }

        departmentMapper.update(department);

    }




    @Override
    public List<Department> deptTree() {
        // 查询所有放在map中
        List<Department> all = departmentMapper.loadAll();

        HashMap<Long, Department> map = new HashMap<>();

        for (Department department : all) {
            map.put(department.getId(),department);
        }

        ArrayList<Department> deptTree = new ArrayList<>();

        for (Department department : all) {
            if(department.getParent_id()==null){ // 顶级部门
                deptTree.add(department);
            }else {
                // 获取顶级部门id
                Long parent_id = department.getParent_id();
                // 从map中获取父部门
                Department parentDepartment = map.get(parent_id);
                // 将自己装到  父部门 的children中
                parentDepartment.getChildren().add(department);

            }

        }


        return deptTree;
    }
}
